import {createWebHashHistory, createWebHistory} from "vue-router";

/** 获取路由历史模式 https://next.router.vuejs.org/zh/guide/essentials/history-mode.html */
export function getHistoryMode(routerHistory) {
    // len为1 代表只有历史模式 为2 代表历史模式中存在base参数 https://next.router.vuejs.org/zh/api/#%E5%8F%82%E6%95%B0-1
    const historyMode = routerHistory.split(",");
    const leftMode = historyMode[0];
    const rightMode = historyMode[1];
    // no param
    if (historyMode.length === 1) {
        if (leftMode === "hash") {
            return createWebHashHistory("");
        } else if (leftMode === "h5") {
            return createWebHistory("");
        }
    } //has param
    else if (historyMode.length === 2) {
        if (leftMode === "hash") {
            return createWebHashHistory(rightMode);
        } else if (leftMode === "h5") {
            return createWebHistory(rightMode);
        }
    }
}

/**
 * 通过path查找路由信息
 * @param {String} path 路径
 * @param {Array} routes 路由列表
 */
export function findRouteByPath(path, routes){
    let res = routes.find(item => item.path === path)
    if (res) return isProxy(res) ? toRaw(res) : res;
    else {
        routes.forEach(item => {
            if (item.children instanceof Array && item.children.length > 0){
                res = findRouteByPath(path, item.children)
                if (res) return isProxy(res) ? toRaw(res) : res;
            }
        })
        return null
    }
}

/**
 * 通过指定 `key` 获取父级路径集合，默认 `key` 为 `path` (嵌套数组)
 * @param {String} value 查找值
 * @param {Array} routes 路由列表
 * @param {String} key 查找键 默认path
 */
export function getParentPaths(value, routes, key = "path") {
    // 深度遍历查找
    function dfs(routes, value, parents) {
        for (let i = 0; i < routes.length; i++) {
            const item = routes[i];
            // 返回父级path
            if (item[key] === value) {
                return parents;
            }
            // children不存在或为空则不递归
            if (!item.children || !item.children.length) continue;
            // 往下查找时将当前path入栈
            parents.push(item.path);

            if (dfs(item.children, value, parents).length) return parents;
            // 深度遍历查找未找到时当前path 出栈
            parents.pop();
        }
        // 未找到时返回空数组
        return [];
    }

    return dfs(routes, value, []);
}



/**
 * 一维数组处理成多级嵌套数组（三级及以上的路由全部拍成二级，keep-alive 只支持到二级缓存）
 * https://github.com/pure-admin/vue-pure-admin/issues/67
 * @param routesList 处理后的一维路由菜单数组
 * @returns {*|[]} 返回将一维数组重新处理成规定路由的格式
 */
 export function formatTwoStageRoutes(routesList) {
    if (routesList.length === 0) return routesList;
    const newRoutesList = [];
    routesList.forEach((v) => {
        if (v.path === "/") {
            newRoutesList.push({
                component: v.component,
                name: v.name,
                path: v.path,
                redirect: v.redirect,
                meta: v.meta,
                children: []
            });
        } else {
            newRoutesList[0]?.children.push({ ...v });
        }
    });
    return newRoutesList;
}

/**
 * 将多级嵌套路由处理成一维数组
 * @param routesList 传入路由
 * @returns {[]} 创建层级关系后的树
 */
export function formatFlatteningRoutes(routesList) {
    if (routesList.length === 0) return routesList;
    let hierarchyList = buildHierarchyTree(routesList) || [];
    for (let i = 0; i < hierarchyList.length; i++) {
        if (hierarchyList[i].children) {
            hierarchyList = hierarchyList
                .slice(0, i + 1)
                .concat(hierarchyList[i].children, hierarchyList.slice(i + 1));
        }
    }
    return hierarchyList;
}

/**
 * @description 创建层级关系
 * @param tree 树
 * @param pathList 每一项的id组成的数组
 * @returns 创建层级关系后的树
 */
export const buildHierarchyTree = (tree, pathList = []) => {
    if (!Array.isArray(tree)) {
        console.warn("tree must be an array");
        return [];
    }
    if (!tree || tree.length === 0) return [];
    for (const [key, node] of tree.entries()) {
        node.id = key;
        node.parentId = pathList.length ? pathList[pathList.length - 1] : null;
        node.pathList = [...pathList, node.id];
        const hasChildren = node.children && node.children.length > 0;
        if (hasChildren) {
            buildHierarchyTree(node.children, node.pathList);
        }
    }
    return tree;
};

/**
 * 路径格式化
 * @param p 路径
 */
export function getNormalPath(p) {
    if (p.length === 0 || !p || p === 'undefined') return ''
    let res = p.replace('//', '/')
    if (res[res.length - 1] === '/') return res.slice(0, res.length - 1)
    return res
}

/**
 * 获取路由列表中的粘性路由(固定在页签的路由)
 * @param routes 路由列表
 * @param basePath 父级路由
 */
export function filterAffixTags(routes, basePath = '') {
    let tags = []
    routes.forEach(route => {
        if (route.meta && route.meta.affix) {
            const tagPath = getNormalPath(basePath + '/' + route.path)
            tags.push({
                fullPath: tagPath,
                path: tagPath,
                name: route.name,
                meta: { ...route.meta }
            })
        }
        if (route.children) {
            const tempTags = filterAffixTags(route.children, route.path)
            if (tempTags.length >= 1) {
                tags = [...tags, ...tempTags]
            }
        }
    })
    return tags
}


